package com.ruoyi.circle.task;

import com.ruoyi.circle.mapper.CircleTagsRelMapper;
import com.ruoyi.classify.mapper.HsContentTagMapper;
import com.ruoyi.digest.mapper.HsGeneratedTextMapper;
import com.ruoyi.pushRecord.domain.CircleHsPushRecord;
import com.ruoyi.pushRecord.mapper.CircleHsPushRecordMapper;
import com.ruoyi.pushSetting.dao.ICircleHsPushSettingDao;
import com.ruoyi.pushSetting.domain.CircleHsPushSetting;
import com.ruoyi.question.domain.QuestionInfo;
import com.ruoyi.question.mapper.QuestionInfoMapper;
import com.ruoyi.questionPushRecord.domain.CircleQuestionPushRecord;
import com.ruoyi.questionPushRecord.mapper.CircleQuestionPushRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 圈子推送任务
 * 
 * @author 区嘉盛
 * @date 2025-06-24
 */
@Component
public class CirclePushTask {
    @Autowired
    private ICircleHsPushSettingDao circleHsPushSettingDao;
    
    @Autowired
    private CircleTagsRelMapper circleTagsRelMapper;
    
    @Autowired
    private HsContentTagMapper hsContentTagMapper;
    
    @Autowired
    private HsGeneratedTextMapper hsGeneratedTextMapper;
    
    @Autowired
    private CircleHsPushRecordMapper circleHsPushRecordMapper;
    
    @Autowired
    private QuestionInfoMapper questionInfoMapper;
    
    @Autowired
    private CircleQuestionPushRecordMapper circleQuestionPushRecordMapper;

    private static final int BATCH_SIZE = 100;
    
    /**
     * 推送AI生成文章到所有圈子
     * 该方法由定时任务调度执行
     */
    @Transactional(rollbackFor = Exception.class)
    public void pushHotSearchTopicToCircles() {
        // 1. 查询所有开启了推送功能的圈子设置
        CircleHsPushSetting query = new CircleHsPushSetting();
        query.setPushStatus(1L); // 推送功能开启
        List<CircleHsPushSetting> pushSettings = circleHsPushSettingDao.selectCircleHsPushSettingList(query);

        if (pushSettings == null || pushSettings.isEmpty()) {
            return;
        }

        // 当前时间
        LocalTime currentTime = LocalTime.now();
        // 当前时间的小时和分钟
        int currentHour = currentTime.getHour();
        int currentMinute = currentTime.getMinute();

        // 收集需要推送的圈子ID
        List<Long> circlesToPush = new ArrayList<>();
        for (CircleHsPushSetting setting : pushSettings) {
            // 检查是否到达推送时间（小时和分钟匹配）
            LocalTime pushTime = setting.getPushTime();
            if (pushTime != null && pushTime.getHour() == currentHour && pushTime.getMinute() == currentMinute) {
                circlesToPush.add(setting.getCircleId());
            }
        }
        
        // 批量推送到多个圈子
        if (!circlesToPush.isEmpty()) {
            // 分批处理圈子，每批最多处理BATCH_SIZE个圈子
            for (int i = 0; i < circlesToPush.size(); i += BATCH_SIZE) {
                int endIndex = Math.min(i + BATCH_SIZE, circlesToPush.size());
                List<Long> batchCircles = circlesToPush.subList(i, endIndex);
                batchPushHotSearchToCircles(batchCircles);
            }
        }
    }

    /**
     * 批量为多个圈子推送热搜主题AI生成文章
     *
     * @param circleIds 圈子ID列表
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchPushHotSearchToCircles(List<Long> circleIds) {
        try {
            // 用于收集所有需要插入的推送记录
            List<CircleHsPushRecord> recordsToInsert = new ArrayList<>();
            
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            LocalDateTime now = LocalDateTime.now();
            
            // 为每个圈子处理推送
            for (Long circleId : circleIds) {
                // 1. 获取圈子的所有标签ID
                List<Long> tagIds = circleTagsRelMapper.selectTagIdsByCircleId(circleId);
                if (tagIds == null || tagIds.isEmpty()) {
                    continue;
                }

                // 2. 通过已验证的标签ID获取相关的热搜主题ID
                List<Long> topicIds = hsContentTagMapper.selectTopicIdsByTagIds(tagIds);
                if (topicIds == null || topicIds.isEmpty()) {
                    continue;
                }

                // 为每个主题创建潜在的推送记录
                for (Long topicId : topicIds) {
                    // 获取该主题当天的所有AI生成文本
                    List<Map<String, Object>> contentList = hsGeneratedTextMapper.selectContentListByTopicIdAndDate(topicId, currentDate);

                    // 如果找到了当天的AI生成文本，则为每个文本创建推送记录
                    if (contentList != null && !contentList.isEmpty()) {
                        for (Map<String, Object> contentMap : contentList) {
                            if (contentMap != null && !contentMap.isEmpty() && contentMap.containsKey("id")) {
                                // 获取AI生成文本ID
                                Long generatedTextId = (Long) contentMap.get("id");
                                
                                // 创建推送记录对象
                                CircleHsPushRecord pushRecord = new CircleHsPushRecord();
                                pushRecord.setCircleId(circleId);
                                pushRecord.setTopicId(topicId);
                                pushRecord.setGeneratedTextId(generatedTextId);
                                pushRecord.setPushTime(now);
                                pushRecord.setPushStatus(1L); // 推送成功
                                pushRecord.setCreatedBy("SYSTEM");
                                pushRecord.setDeletedFlag(0L);
                                
                                // 添加到待插入列表
                                recordsToInsert.add(pushRecord);
                                
                                // 如果待插入记录达到批量大小，先处理一批
                                if (recordsToInsert.size() >= BATCH_SIZE) {
                                    processBatchRecords(recordsToInsert);
                                    // 清空列表，准备下一批
                                    recordsToInsert.clear();
                                }
                            }
                        }
                    }
                }
            }
            
            // 处理剩余的记录
            if (!recordsToInsert.isEmpty()) {
                processBatchRecords(recordsToInsert);
                
                // 同步推送AI生成文章配套的题目
                batchPushQuestionsToCircles(recordsToInsert);
            }

        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
        }
    }
    
    /**
     * 处理一批推送记录
     * 
     * @param recordsToInsert 待处理的推送记录列表
     */
    @Transactional(rollbackFor = Exception.class)
    public void processBatchRecords(List<CircleHsPushRecord> recordsToInsert) {
        // 批量检查重复记录
        List<Map<String, Object>> existingRecords = circleHsPushRecordMapper.batchCheckDuplicatePushRecords(recordsToInsert);
        
        // 如果有重复记录，过滤掉
        if (existingRecords != null && !existingRecords.isEmpty()) {
            // 创建一个集合来存储已存在的记录的唯一标识
            Map<String, Boolean> existingMap = new HashMap<>();
            for (Map<String, Object> record : existingRecords) {
                String key = record.get("circle_id") + "-" + record.get("topic_id") + "-" + record.get("generated_text_id");
                existingMap.put(key, true);
            }
            
            // 过滤掉已存在的记录
            recordsToInsert = recordsToInsert.stream().filter(record -> {
                String key = record.getCircleId() + "-" + record.getTopicId() + "-" + record.getGeneratedTextId();
                return !existingMap.containsKey(key);
            }).collect(Collectors.toList());
        }
        
        // 批量插入非重复记录
        if (!recordsToInsert.isEmpty()) {
            circleHsPushRecordMapper.batchInsertCircleHsPushRecord(recordsToInsert);
            System.out.println("成功批量插入" + recordsToInsert.size() + "条推送记录");
        }
    }
    
    /**
     * 批量推送AI生成文章配套的题目到圈子
     *
     * @param hsPushRecords AI生成文章推送记录列表
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchPushQuestionsToCircles(List<CircleHsPushRecord> hsPushRecords) {
        try {
            // 用于收集所有需要插入的题目推送记录
            List<CircleQuestionPushRecord> recordsToInsert = new ArrayList<>();
            
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            
            // 为每个AI生成文章推送记录处理题目推送
            for (CircleHsPushRecord hsPushRecord : hsPushRecords) {
                Long circleId = hsPushRecord.getCircleId();
                Long generatedTextId = hsPushRecord.getGeneratedTextId();
                
                // 查询该AI生成文章关联的题目
                QuestionInfo queryParam = new QuestionInfo();
                queryParam.setGeneratedTextId(generatedTextId);
                queryParam.setDeletedFlag(0L);
                queryParam.setQuestionStatus(1L);
                List<QuestionInfo> questions = questionInfoMapper.selectQuestionInfoList(queryParam);
                
                if (questions == null || questions.isEmpty()) {
                    continue;
                }
                
                // 为每个题目创建推送记录
                for (QuestionInfo question : questions) {
                    // 创建题目推送记录对象
                    CircleQuestionPushRecord pushRecord = new CircleQuestionPushRecord();
                    pushRecord.setCircleId(circleId);
                    pushRecord.setQuestionId(question.getId());
                    pushRecord.setGeneratedTextId(generatedTextId);
                    pushRecord.setPushTime(LocalDateTime.now());
                    pushRecord.setPushStatus(1L); // 推送成功
                    pushRecord.setCreatedBy("SYSTEM");
                    pushRecord.setDeletedFlag(0L);
                    
                    // 添加到待插入列表
                    recordsToInsert.add(pushRecord);
                    
                    // 如果待插入记录达到批量大小，先处理一批
                    if (recordsToInsert.size() >= BATCH_SIZE) {
                        processQuestionBatchRecords(recordsToInsert);
                        // 清空列表，准备下一批
                        recordsToInsert.clear();
                    }
                }
            }
            
            // 处理剩余的记录
            if (!recordsToInsert.isEmpty()) {
                processQuestionBatchRecords(recordsToInsert);
            }
            
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
        }
    }
    
    /**
     * 处理一批题目推送记录
     * 
     * @param recordsToInsert 待处理的题目推送记录列表
     */
    @Transactional(rollbackFor = Exception.class)
    public void processQuestionBatchRecords(List<CircleQuestionPushRecord> recordsToInsert) {
        // 批量检查重复记录
        List<Map<String, Object>> existingRecords = circleQuestionPushRecordMapper.batchCheckDuplicatePushRecords(recordsToInsert);
        
        // 如果有重复记录，过滤掉
        if (existingRecords != null && !existingRecords.isEmpty()) {
            // 创建一个集合来存储已存在的记录的唯一标识
            Map<String, Boolean> existingMap = new HashMap<>();
            for (Map<String, Object> record : existingRecords) {
                String key = record.get("circle_id") + "-" + record.get("question_id") + "-" + record.get("generated_text_id");
                existingMap.put(key, true);
            }
            
            // 过滤掉已存在的记录
            recordsToInsert = recordsToInsert.stream().filter(record -> {
                String key = record.getCircleId() + "-" + record.getQuestionId() + "-" + record.getGeneratedTextId();
                return !existingMap.containsKey(key);
            }).collect(Collectors.toList());
        }
        
        // 批量插入非重复记录
        if (!recordsToInsert.isEmpty()) {
            circleQuestionPushRecordMapper.batchInsertCircleQuestionPushRecord(recordsToInsert);
            System.out.println("成功批量插入" + recordsToInsert.size() + "条题目推送记录");
        }
    }
}
